"use client"

import {useAuth, UserButton, useUser} from "@clerk/nextjs";
import ThemeSwitcher from "@/components/ThemeSwitcher";
import {
    Button,
    Spacer,
    useDisclosure,
    Modal,
    ModalContent,
    ModalHeader,
    ModalFooter,
    ModalBody,
    Textarea,
    Input,
    Chip, Divider
} from "@nextui-org/react";
import {FileUp, Send} from "lucide-react";
import {useEffect, useState} from "react";
import {CldUploadButton} from "next-cloudinary";
import type {CloudinaryUploadWidgetResults} from "next-cloudinary"
import {CloudinaryUploadWidgetInfo} from "@cloudinary-util/types/src/types/cloudinary-upload-widget";
import {Topic} from "@/util/type";
import TicketTopics from "@/components/TicketTopics";

export default function Home() {
    const {userId} = useAuth()
    const avatar = useUser().user?.imageUrl
    const {isOpen, onOpen, onOpenChange} = useDisclosure();
    const [topicContent, setTopicContent] = useState("")
    const [currentOptionValue, setCurrentOptionValue] = useState("")
    const [optionsValue, setOptionsValue] = useState<string[]>([])
    const [images, setImages] = useState<string[]>([])
    const [topics, setTopics] = useState<Topic[]>([])

    // 处理上传成功的图片
    const handleUploadSuccess = (results: CloudinaryUploadWidgetResults) => {
        // 将上传成功得图片地址进行保存
        const info = results.info as CloudinaryUploadWidgetInfo
        if (info.secure_url) {
            setImages((images) => [
                ...images,
                info.secure_url
            ])
        }
    }

    // 发布话题
    const handleRelease = async (onClose: () => void) => {
        // 发起请求
        const res = await fetch(process.env.API_ADDRESS + "/topic", {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                userId,
                avatar,
                content: topicContent,
                images: images.join(","),
                options: optionsValue
            })
        })
        const topic = (await res.json()).topic as Topic
        setTopics([
            ...topics,
            topic
        ])
        // 将表单清空
        setTopicContent("")
        setCurrentOptionValue("")
        setImages([])
        setOptionsValue([])
        onClose()
    }

    // 根据话题id查询话题
    const getTopicById = async (topicId: string) => {
        const res = await fetch(`${process.env.API_ADDRESS}/topic/${topicId}?userId=${userId}`, {
            method: "GET",
            cache: "no-cache",
        })
        const data = (await res.json()).topic as Topic
        topics.some((topic) => {
            if (topic.id === data.id) {
                topic.options = data.options
                setTopics([...topics])
                return true
            }
        })
    }

    // 初始化话题数据
    useEffect(() => {
        fetch(process.env.API_ADDRESS + "/topic?userId=" + userId, {
            method: "GET",
            cache: "no-cache"
        }).then((res) => {
            res.json().then(data => {
                setTopics(data.topics as Topic[])
            })
        })
    }, [])

    return (
        <>
            <header className="w-full h-14">
                <div className="fixed top-4 right-8 flex justify-center items-center">
                    <Button color="success" endContent={<Send/>} onPress={onOpen}>发布</Button>
                    <Spacer x={4}/>
                    <ThemeSwitcher/>
                    <Spacer x={4}/>
                    <UserButton/>
                </div>
            </header>
            <div className="m-4 flex justify-center items-center">
                <main className="flex justify-center items-center flex-col border-x-2 sm:w-full md:w-9/12 lg:w-6/12">
                    <Divider className="my-5"/>
                    {
                        topics.map((topic, index) => {
                            return <TicketTopics key={index} topic={topic} getTopicById={getTopicById} />
                        })
                    }
                </main>
            </div>
            <Modal isOpen={isOpen} onOpenChange={onOpenChange}>
                <ModalContent>
                    {
                        (onClose) => (
                            <>
                                <ModalHeader className="flex flex-col gap-1">发布话题</ModalHeader>
                                <ModalBody>
                                    <Textarea
                                        label="输入内容"
                                        placeholder="写一段话题吧！"
                                        labelPlacement="inside"
                                        variant="underlined"
                                        value={topicContent}
                                        onValueChange={setTopicContent}
                                    />
                                    <Spacer x={2}/>
                                    <CldUploadButton
                                        uploadPreset="lblb5spm"
                                        onSuccess={handleUploadSuccess}
                                    >
                                        <button className="bg-secondary-400 hover:bg-secondary-700 text-white font-bold py-2 px-4 rounded-full">
                                            <div className="flex items-center justify-center">
                                                <FileUp/>
                                                <span>上传图片</span>
                                            </div>
                                        </button>
                                    </CldUploadButton>
                                    <Spacer x={2}/>
                                    <div className="flex items-center">
                                        <Input
                                            label="输入选项"
                                            variant={"faded"}
                                            size="sm"
                                            value={currentOptionValue}
                                        onValueChange={setCurrentOptionValue}/>
                                        <Spacer y={2}/>
                                        <Button color="success" onPress={() => {
                                            if (!currentOptionValue) return
                                            setOptionsValue([
                                                ...optionsValue,
                                                currentOptionValue
                                            ])
                                            setCurrentOptionValue("")
                                        }}>添加</Button>
                                    </div>
                                    <Spacer x={2}/>
                                    <div className="flex gap-2 flex-wrap">
                                        {
                                            optionsValue.map((item, index) => {
                                                return <Chip color="success" variant={"faded"} key={index} onClose={() => {
                                                    setOptionsValue(optionsValue.filter(value => value !== item))
                                                }}>{item}</Chip>
                                            })
                                        }
                                    </div>
                                </ModalBody>
                                <ModalFooter>
                                    <Button color="danger" variant="light" onPress={onClose}>
                                        取消
                                    </Button>
                                    <Button color="primary" onPress={() => handleRelease(onClose)}>发布</Button>
                                </ModalFooter>
                            </>
                        )
                    }
                </ModalContent>
            </Modal>
        </>
    );
}
